<!--
 * @Author: 王鹏 2911783749@qq.com
 * @Date: 2022-10-24 16:39:47
 * @LastEditors: 王鹏 2911783749@qq.com
 * @LastEditTime: 2022-10-26 19:57:05
 * @FilePath: \v_shop\code\src\components\children\Roles.vue
 * @Description: 角色列表页
-->

<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showRolesModule"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="rolesList" border max-height="450">
        <el-table-column type="expand">
          <!-- 展开项 -->
          <template slot-scope="scope">
            <!-- 遍历一级权限 -->
            <el-row
              :class="[i1 === 0 ? '' : 'bdtop', 'vcenter']"
              v-for="(firstItem, i1) in scope.row.children"
              :key="firstItem.id"
            >
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightById(scope.row, firstItem.id)"
                  >{{ firstItem.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 遍历二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(secondItem, i2) in firstItem.children"
                  :key="secondItem.id"
                >
                  <!-- 二级权限名字 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, secondItem.id)"
                      >{{ secondItem.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 遍历三级权限 -->
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, thirdItem.id)"
                      v-for="thirdItem in secondItem.children"
                      :key="thirdItem.id"
                    >
                      {{ thirdItem.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName" align="center">
        </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc" align="center">
        </el-table-column>
        <el-table-column label="操作" align="center" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRoles(scope.$index, scope.row)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="delRoles(scope.$index, scope.row)"
              >删除</el-button
            >
            <!-- 分配权限按钮 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-share"
              @click="showDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹窗组件 -->
      <RolesDialog
        :rolesForm="rolesForm"
        :dialog="dialog"
        @update="getRolesList"
      />
      <!-- 分配权限弹框 -->
      <el-dialog title="分配权限" :visible.sync="dialogVisible" width="50%" @close="clearDefaultKeys">
        <!--  -->
        <el-tree
          :data="rightsTree"
          :props="treesProps"
          show-checkbox
          default-expand-all
          node-key="id"
          :default-checked-keys="defaultKeys"
          ref="treeData"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { roles, del_roles, deleteRights, get_rightstree,add_roleRights } from "../../http/api";
import RolesDialog from "../../views/RolesDialog.vue";
export default {
  name: "Roles",
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 角色模态框表单数据
      rolesForm: {
        roleName: "",
        roleDesc: "",
      },
      // 角色模态框属性
      dialog: {
        show: false,
        title: "编辑角色",
        option: "edit",
      },
      // 分配权限弹框
      dialogVisible: false,
      // 树状权限数据
      rightsTree: [],
      // 靶子对象
      treesProps: {
        label: "authName",
        children: "children",
      },
      // 默认勾选数组
      defaultKeys:[],
      // 角色id
      roleId:"",
    };
  },

  components: { RolesDialog },

  computed: {},

  mounted() {
    this.getRolesList();
  },

  methods: {
    // 删除权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let { data: res } = await deleteRights(role.id, rightId);
          console.log(res, "del");
          if (res.meta.status !== 200) {
            return this.$message.error("删除权限失败");
          }
          role.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 调取角色数据
    getRolesList() {
      roles().then((res) => {
        console.log(res);
        this.rolesList = res.data.data;
      });
    },
    // 点击添加角色按钮
    showRolesModule() {
      // 初始化表单数据
      (this.rolesForm = {
        roleName: "",
        roleDesc: "",
      }),
        // 更改模态框属性
        (this.dialog = {
          show: true,
          title: "添加角色",
          option: "add",
        });
    },
    // 编辑数据回显
    editRoles(index, value) {
      (this.rolesForm = {
        id: value.id,
        roleName: value.roleName,
        roleDesc: value.roleDesc,
      }),
        (this.dialog = {
          show: true,
          title: "编辑角色",
          option: "edit",
        });
    },
    // 删除角色
    delRoles(index, value) {
      del_roles(value).then((res) => {
        console.log(res);
        if (res.data.meta.status != 200) {
          return this.$message.error(res.data.meta.msg);
        }
        this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$message({
              type: "success",
              message: res.data.meta.msg,
            });
            this.getRolesList();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      });
    },
    // 打开分配权限对话框
    async showDialog(role) {
      this.roleId=role.id
      this.dialogVisible = true;
      let { data: res } = await get_rightstree();
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.success("获取权限列表菜单失败");
      }
      this.rightsTree = res.data;
      this.getleafKeys(role,this.defaultKeys)
    },
    // 递归便利三级节点，如果没有children就是三级节点 那么渲染数组
    getleafKeys(node,arr){
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getleafKeys(item,arr)
      })
      // console.log(arr,"keys");
    },
    // 关闭弹框，清除默认选中
    clearDefaultKeys(){
      this.defaultKeys=[]
    },
    // 添加权限
    async addRights(){
      let key=[
        ...this.$refs.treeData.getCheckedKeys(),
        ...this.$refs.treeData.getHalfCheckedKeys()
      ];
      // console.log(key);
      let idStr=key.join(',')
      // console.log(idStr);
      let {data:res}=await add_roleRights(this.roleId,{rids:idStr})
      if(res.meta.status!==200){
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.dialogVisible=false
      this.getRolesList()
    },
  },
  watch: {},
  mixins: [],
};
</script>
<style  scoped>
.el-card {
  margin-top: 20px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  padding: 6px;
}
</style>